package org.meb.spdwldr;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;

import org.meb.spdwldr.core.SortOrder;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/event")
public class EventSourceController {

	private EventsListFilter filter;
	private SortOrder defaultSortOrder;

	public EventSourceController() {
		defaultSortOrder = new SortOrder();
		defaultSortOrder.desc("eventDate");
		defaultSortOrder.asc("eventGroup");
		defaultSortOrder.asc("eventTime");
		defaultSortOrder.asc("eventName");
	}

	private static final SimpleDateFormat outFmt = new SimpleDateFormat("dd.MM.");
	private static TimeZone timeZone = TimeZone.getTimeZone("CET");

	@InitBinder
	public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Date.class, "eventDate", new CustomDateEditor(
				new SimpleDateFormat("yyyyMMddHHmm"), false));
	}

	@RequestMapping(value = "/put", method = RequestMethod.POST, params = "batch")
	public @ResponseBody
	String putBatch(EventSource eventSource, BindingResult result) {
		if (result.hasErrors()) {
			return "ERROR";
		}

		String uri = eventSource.getEventUri();
		if (uri == null) {
			return "ERROR: uri missing";
		}
		String name = eventSource.getEventName();
		if (name == null) {
			return "ERROR: name missing";
		}
		String group = eventSource.getEventGroup();
		if (group == null) {
			return "ERROR: group missing";
		}
		Date date = eventSource.getEventDate();
		if (date == null) {
			return "ERROR: date missing";
		}

		EventSource source = new EventSourceDao().find(uri);
		if (source == null) {
			source = new EventSource();
		}
		source.setEventUri(uri);
		source.setEventName(name);
		source.setEventGroup(group);
		source.setEventDate(date);
		boolean insert = source.getId() == null;
		new EventSourceDao().merge(source);

		return "OK: " + (insert ? "insert" : "update") + ": " + eventSource.toString();
	}

	@RequestMapping(value = "/put", method = RequestMethod.POST)
	public ModelAndView put(EventSource eventSource, BindingResult result) {
		return getEventSources();
	}

	// @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	// public String deleteEventSource(@PathVariable("id") Long id) {
	// new EventSourceDao().delete(id);
	// return "redirect:/event/list";
	// }

	@RequestMapping("/list")
	public ModelAndView getEventSources() {
		EventSourceQuery query = new EventSourceQuery();
		query.setSortOrder(defaultSortOrder);
		List<EventSource> eventSources = new EventSourceDao().find(query);
		ModelAndView mav = new ModelAndView("events");
		mav.addObject("eventSources", eventSources);
		mav.addObject("timeZone", timeZone);
		return mav;
	}

	@RequestMapping(value = "/list", params = "grp")
	public ModelAndView getEventSourceGroups() {
		EventSourceQuery query = new EventSourceQuery();
		query.setSortOrder(defaultSortOrder);
		ArrayList<Group> groups = new ArrayList<Group>();
		List<EventSource> sources = new EventSourceDao().find(query);
		String name = null;
		Group group = null;
		for (EventSource source : sources) {
			outFmt.setTimeZone(timeZone);
			if (source.getEventDate() == null) {
				name = "(DATE MISSING) " + source.getEventGroup();
			} else {
				name = outFmt.format(source.getEventDate()) + " " + source.getEventGroup();
			}
			if (group == null || !name.equals(group.getName())) {
				group = new Group();
				group.setName(name);
				group.setEventSources(new ArrayList<EventSource>());
				groups.add(group);
			}
			group.getEventSources().add(source);
		}

		ModelAndView mav = new ModelAndView("eventsgrp");
		mav.addObject("eventSourceGroups", groups);
		mav.addObject("timeZone", timeZone);
		return mav;
	}

	public void setFilter(EventsListFilter filter) {
		this.filter = filter;
	}
}
